//
// Created by 26090 on 24-12-14.
//

#include "bsp_pwm.h"
#include "bsp_log.h"
#include "memory.h"

#define DEVICE_PWM_CNT 4

static uint8_t idx;
static PWMInstance *pwm_instance[10];

PWMInstance *PWMRegister(PWM_Init_Config_s *init_config)
{
    if (idx >= DEVICE_PWM_CNT) // 超过最大实例数
        while (1)
            LOGERROR("[bsp_usart] USART exceed max instance count!");
    for (uint8_t i = 0; i < idx; i++) // 检查是否已经注册过
        if (pwm_instance[i]->tim_handle == init_config->tim_handle && pwm_instance[i]->channel==init_config->channel)
        {
            return pwm_instance[i];
        }
    PWMInstance *instance = (PWMInstance *)malloc(sizeof(PWMInstance));
    memset(instance, 0, sizeof(PWMInstance));

    instance->tim_handle = init_config->tim_handle;
    instance->channel = init_config->channel;
    instance->frequency=(float)HAL_RCC_GetPCLK1Freq();
    instance->duty=0;

    HAL_TIM_PWM_Start(instance->tim_handle, instance->channel);
    pwm_instance[idx++] = instance;
    return instance;
}

void PWM_SetDuty(PWMInstance *instance, const float duty)
{
    uint32_t arr =__HAL_TIM_GetAutoreload(instance->tim_handle)+1;
    uint32_t ccr= duty * arr;
    __HAL_TIM_SetCompare(instance->tim_handle, instance->channel, ccr);
    instance->duty = duty;
}
